package com.onlyphoto.onlymall.mvp.view.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.AsyncTask
import android.os.Build
import android.os.Environment
import android.os.Looper
import android.text.Html
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.content.PermissionChecker.PERMISSION_GRANTED
import com.onlyphoto.onlymall.BuildConfig
import com.onlyphoto.onlymall.R
import com.onlyphoto.onlymall.base.BaseActivity
import com.onlyphoto.onlymall.bean.response.AppUpdateBean
import com.onlyphoto.onlymall.mvp.contract.CSetting
import com.onlyphoto.onlymall.mvp.presenter.PSettingImpl
import com.onlyphoto.onlymall.utils.*
import com.onlyphoto.onlymall.widget.AlertDialog
import com.onlyphoto.onlymall.widget.AppUpdateProgressDialog
import kotlinx.android.synthetic.main.activity_setting.*
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL


class SettingActivity : BaseActivity<PSettingImpl>(), CSetting.IVSetting, View.OnClickListener {

    var TAG = "SettingActivity"
    var updateProgressDialog: AppUpdateProgressDialog? = null
    private var isSetPwd = 0
    private var isPhoneLogin = true
    private var phone = ""

    override fun retry() {}

    @SuppressLint("SetTextI18n")
    override fun init() {
        app_version.text = "V${BuildConfig.VERSION_NAME}"
    }

    override fun initListener() {
        //点击事件初始化
        login_out.setOnClickListener(this)
        back.setOnClickListener(this)
        set_pwd.setOnClickListener(this)
        update_pwd.setOnClickListener(this)
        app_update.setOnClickListener(this)
        qr_code.setOnClickListener(this)
    }

    override fun onResume() {
        super.onResume()
        isSetPwd = SharePreferenceUtil.getInstance(this).getIntData(Constants.IS_SET_PWD, 0)
        isPhoneLogin = SharePreferenceUtil.getInstance(this).getBoolData(Constants.IS_PHONE_LOGIN, true)
        if (isPhoneLogin) {
            if (isSetPwd == 0) {
                set_pwd.visibility = View.VISIBLE
                update_pwd.visibility = View.GONE
            } else {
                set_pwd.visibility = View.GONE
                update_pwd.visibility = View.VISIBLE
            }
            phone = SharePreferenceUtil.getInstance(this).getData(Constants.SHARE_TAG_LOGIN_PHONE)
            phone_num.text = StringUtil.getHiddenPhone(phone)
        } else {
            set_pwd.visibility = View.GONE
            update_pwd.visibility = View.GONE
            fl_phone.visibility = View.GONE
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.login_out -> {
                AlertDialog(this).builder()
                        .setTitle("确认退出登录？")
                        .setCanceledOnTouchOutside(false)
                        .setNegativeButton("取消") {}
                        .setPositiveButton("确定") {
                            UserUtil.logout(this)
                            finish()
                        }.show()
            }
            R.id.back -> finish()
            R.id.set_pwd -> { startActivity(Intent(this, SetPwdActivity::class.java))}
            R.id.update_pwd -> { startActivity(Intent(this, UpdatePwdActivity::class.java)) }
            R.id.app_update -> {
                //测试数据
                /*val bean = AppUpdateBean()
                bean.hasUpgrade = 1
                bean.isForceUpgrade = 1
                bean.newVersion = "1.0.1"
                bean.newFeatures = "更新了版本更新"
                bean.appUrl = "https://mall201906.oss-cn-shanghai.aliyuncs.com/apk/onlyMall.apk"
                updateVersion(bean)*/
                //跳转至应用市场
                toMarket(this, "com.onlyphoto.onlymall", null)
                //mPresenter?.getAppUpdateInfo()
            }
            R.id.qr_code -> {
                //二维码的背景图片
                val bmp = BitmapFactory.decodeResource(resources, R.mipmap.app_logo)
                //生成的二维码图片
                val qr = QRCodeUtil.createQRImage("https://mall201906.oss-cn-shanghai.aliyuncs.com/apk/onlyMall.apk", 350, 350, bmp)
                startActivity(Intent(this, QRCodeActivity::class.java)
                        .putExtra("bitmap", qr))

            }
        }
    }

    private fun toMarket(context: Context, appPkg: String, marketPkg: String?): Boolean {
        val uri = Uri.parse("market://details?id=$appPkg")
        val intent = Intent(Intent.ACTION_VIEW, uri)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        if (marketPkg != null) {   // 如果没给市场的包名，则系统会弹出市场的列表让你进行选择。
            intent.setPackage(marketPkg)
        }
        return try {
            context.startActivity(intent)
            true
        } catch (ex: Exception) {
            ex.printStackTrace()
            false
        }

    }

    override fun getAppUpdateInfoSuccess(bean: AppUpdateBean) {
        updateVersion(bean)
    }

    private var downloadTask : AsyncTask<String, Int, Unit>? = null

    private fun updateVersion(bean: AppUpdateBean) {
        if (!StringUtil.compareAppVersion(ViewUtil.getAppVersion(this), bean.newVersion)) {
            return
        }
        if (bean.hasUpgrade == 1) {
            LogUtil.log(TAG, "updateVersion: ")
            updateProgressDialog = AppUpdateProgressDialog()
            if (bean.isForceUpgrade == 1) {
                updateProgressDialog?.isCancelable = false             //强制更新弹窗不消失
                updateProgressDialog?.setCanClose(false)
            }
            downloadTask = @SuppressLint("StaticFieldLeak")
            object : AsyncTask<String, Int, Unit>(){

                val dir = File(SDCardFileUtils.creatDir2SDCard(SDCardFileUtils.CREATE_CARD_PATH))
                val file = File(dir, "onlyMall.apk")

                override fun doInBackground(vararg params: String?) {
                    if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
                        var fileOutputStream: FileOutputStream? = null

                        try {
                            var count = 0
                            val url = URL(bean.appUrl)
                            val conn = url.openConnection() as HttpURLConnection
                            conn.connectTimeout = 20000
                            conn.readTimeout = 20000
                            val isInput = conn.inputStream
                            updateProgressDialog?.setTotal(conn.contentLength)
                            if (isInput != null) {
                                if (file.exists()) {
                                    file.delete()
                                }
                                fileOutputStream = FileOutputStream(file)
                                val buf = ByteArray(4096)
                                var temp: Int
                                fileOutputStream.let { it ->
                                    while (isInput.read(buf).also { temp = it } != -1) {
                                        it.write(buf, 0, temp)
                                        count += temp
                                        publishProgress(count)
                                    }
                                }
                            }
                            fileOutputStream?.flush()
                            fileOutputStream?.close()

                        } catch (e: MalformedURLException) {
                            Looper.prepare()
                            if (bean.isForceUpgrade == 1) {
                                showToast("更新失败，请重新尝试")
                                finish()
                            } else {
                                showToast("更新失败")
                            }
                            e.printStackTrace()
                        } catch (e: IOException) {
                            Looper.prepare()
                            if (bean.isForceUpgrade == 1) {
                                showToast("更新失败，请重新尝试")
                                finish()
                            } else {
                                showToast("更新失败")
                            }
                            e.printStackTrace()
                        } finally {
                            fileOutputStream?.close()
                        }

                    }
                    return
                }

                override fun onPostExecute(result: Unit?) {
                    super.onPostExecute(result)
                    if (file.exists()) {
                        installApk(this@SettingActivity, Environment.getExternalStorageDirectory().path + "/onlyMall/onlyMall.apk")
                    }
                    if (bean.isForceUpgrade == 1) {
                        finish()
                    }
                }

                override fun onProgressUpdate(vararg values: Int?) {
                    super.onProgressUpdate(*values)
                    values[0]?.let {
                        updateProgressDialog?.updateProgress(it)
                    }

                }
            }
            updateProgressDialog?.setDismissCallBack { downloadTask?.cancel(false) }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                updateProgressDialog?.setContent("" + Html.fromHtml(bean.newFeatures, Html.FROM_HTML_MODE_LEGACY))
            } else {
                updateProgressDialog?.setContent("" + Html.fromHtml(bean.newFeatures))
            }
            updateProgressDialog?.setUpdateStartCallBack {
                //申请手机存储权限·
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        // 检查权限状态
                        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            //  用户未彻底拒绝授予权限用户彻底拒绝授予权限，一般会提示用户进入设置权限界面
                            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1);
                        } else {
                            ToastUtil.showToast("请打开该应用存储权限")
                        }
                    } else {
                        updateProgressDialog?.beginDownload()
                        downloadTask?.execute()
                    }
                }
            }
            //DialogFragmentManager.obtain().addDialog(BaseDialogFragmentWrapper(updateProgressDialog, "updateApp", true))
            updateProgressDialog?.show(supportFragmentManager, "app_update", true)
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1) {
            for (i in permissions.indices) {
                if (grantResults[i] == PERMISSION_GRANTED) {
                    updateProgressDialog?.beginDownload()
                    downloadTask?.execute()
                } else {
                    ToastUtil.showToast("请打开该应用存储权限")
                }
            }
        }
    }

    fun installApk(context: Context?, apkPath: String) {
        if (context == null || StringUtil.isBlank(apkPath)) {
            return
        }
        val file = File(apkPath)
        val intent = Intent(Intent.ACTION_VIEW)

        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= 24) {
            //provider authorities
            val apkUri = FileProvider.getUriForFile(context, "com.onlyphoto.onlymall.fileprovider", file)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
        } else {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive")
        }
        context.startActivity(intent)
    }

    override fun loadData() {
        //加载数据
    }

    override fun isFullScreen(): Boolean {
        //是否沉浸式， 默认非沉浸式
        return false
    }

    public override fun initCustomerStatusManager() {

    }

    override fun setContentViewId(): Int {
        return R.layout.activity_setting
    }

    override fun createPresenter() {
        mPresenter = PSettingImpl(mContext, this)
    }

    override fun showLoading() {

    }

    override fun hideLoading() {

    }

    inner class DownloadAsyncTask(var bean: AppUpdateBean) : AsyncTask<String, Int, Unit>() {

        val dir = File(SDCardFileUtils.creatDir2SDCard(SDCardFileUtils.CREATE_CARD_PATH))
        val file = File(dir, "onlyMall.apk")

        override fun doInBackground(vararg params: String?) {
            if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
                var fileOutputStream: FileOutputStream? = null

                try {
                    var count = 0
                    val url = URL(bean.appUrl)
                    val conn = url.openConnection() as HttpURLConnection
                    conn.connectTimeout = 20000
                    conn.readTimeout = 20000
                    val isInput = conn.inputStream
                    updateProgressDialog?.setTotal(conn.contentLength)
                    if (isInput != null) {
                        if (file.exists()) {
                            file.delete()
                        }
                        fileOutputStream = FileOutputStream(file)
                        val buf = ByteArray(4096)
                        var temp: Int
                        fileOutputStream.let { it ->
                            while (isInput.read(buf).also { temp = it } != -1) {
                                it.write(buf, 0, temp)
                                count += temp
                                publishProgress(count)
                            }
                        }
                    }
                    fileOutputStream?.flush()
                    fileOutputStream?.close()

                } catch (e: MalformedURLException) {
                    Looper.prepare()
                    if (bean.isForceUpgrade == 1) {
                        showToast("更新失败，请重新尝试")
                        finish()
                    } else {
                        showToast("更新失败")
                    }
                    e.printStackTrace()
                } catch (e: IOException) {
                    Looper.prepare()
                    if (bean.isForceUpgrade == 1) {
                        showToast("更新失败，请重新尝试")
                        finish()
                    } else {
                        showToast("更新失败")
                    }
                    e.printStackTrace()
                } finally {
                    fileOutputStream?.close()
                }

            }
            return
        }

        override fun onPostExecute(result: Unit?) {
            super.onPostExecute(result)
            if (file.exists()) {
                installApk(this@SettingActivity, Environment.getExternalStorageDirectory().path + "/onlyMall/onlyMall.apk")
            }
            if (bean.isForceUpgrade == 1) {
                finish()
            }
        }

        override fun onProgressUpdate(vararg values: Int?) {
            super.onProgressUpdate(*values)
            values[0]?.let {
                updateProgressDialog?.updateProgress(it)
            }
        }
    }
}
